import functools
from colanderalchemy import SQLAlchemySchemaNode
import deform

from caerp.consts.users import ACCOUNT_TYPES_LABELS
from caerp.models.user import Group
from caerp.forms import (
    customize_field,
    get_sequence_child_item,
    get_deferred_model_select_checkbox,
)
from caerp.models.user.access_right import AccessRight


def get_right_label(access_right: AccessRight):
    label = access_right.label
    for tag in access_right.tags:
        label += f"&nbsp;<span class='icon tag neutral'>{tag}</span>"
    if access_right.rgpd:
        label += "&nbsp;<span class='icon tag caution'>RGPD</span>"

    return label


def customize_schema(schema, request, edit):
    customize = functools.partial(customize_field, schema)
    if "account_type" in schema:
        values = tuple(ACCOUNT_TYPES_LABELS.items())
        values += (("all", "Les deux"),)
        customize(
            "account_type",
            widget=deform.widget.RadioChoiceWidget(values=values),
        )
    elif edit:
        account_type_label = ACCOUNT_TYPES_LABELS.get(
            request.context.account_type, "entrepreneurs et équipe d'appui"
        )
        customize(
            "default_for_account_type",
            title=(
                f"Ce rôle est-il utilisé par défaut pour les "
                f'nouveaux comptes "{account_type_label}" ?'
            ),
        )
    if "access_rights" in schema:
        customize(
            "access_rights",
            title="Drois d'accès",
            children=get_sequence_child_item(AccessRight),
            widget=get_deferred_model_select_checkbox(
                AccessRight, keys=("id", get_right_label)
            ),
        )


def get_add_edit_group_schema(request, edit=False):
    excludes = (
        "id",
        "users",
    )
    if edit:
        excludes += ("account_type",)
    schema = SQLAlchemySchemaNode(Group, excludes=excludes)
    customize_schema(schema, request=request, edit=edit)
    return schema
